package com.xuecheng.mybatis.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.xuecheng.commons.utils.AuthInfoThreadLocal;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.schema.Column;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * mybatis-plus配置类
 *
 * @author 七安
 */
@Configuration
@Slf4j
public class MybatisConfig {

    //不需要拼接机构id的表
    private static String[] tables = new String[]{"tb_dictionary", "tb_category",
            "undo_log", "tb_application", "tb_company", "tb_resource", "tb_role_resource", "tb_user_role"};

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        //多租户插件(这玩意一定要在分页插件之前设置)
        mybatisPlusInterceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
            //要拼接字段的内容
            @Override
            public Expression getTenantId() {
                //从本地线程中获取要拼接的id
                Long companyId = AuthInfoThreadLocal.getCompanyId();
                if (companyId == null) {
                    return null;
                }
                return new StringValue(companyId.toString());
            }

            //要拼接哪个字段
            @Override
            public String getTenantIdColumn() {
                return "company_id";
            }

            //要拼接哪张表，不拼接哪张表(true为忽略，false为拼接)
            @Override
            public boolean ignoreTable(String tableName) {
                //如果传进来的表在tables里存在，就忽略
                if (ArrayUtils.contains(tables, tableName)) {
                    return true;
                }
                //如果companyId为null，也不进行拼接
                Long companyId = AuthInfoThreadLocal.getCompanyId();
                return companyId == null;
            }
        }));
        //分页插件
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return mybatisPlusInterceptor;
    }
}
